package enemies 
{
	import adobe.utils.ProductManager;
	import entities.Entity;
	import flash.geom.Point;
	/**
	 * ...
	 * @author Gareth Williams
	 * this class calculates n points on a circle with a given radius
	 * the perimeter is then divided into an interval and turn angle which 
	 * moves the entity on a path in a similar manner to Lingo (move forward n steps then turn n degrees)
	 */
	public class GeomPath implements IStrategyImplementation 
	{
		private static const TOP_LEFT:uint = 0;
		private static const TOP_RIGHT:uint = 1;
		private static const BTM_RIGHT:uint = 2;
		private static const BTM_LEFT:uint = 3;
		
		private const points:Array = new Array();
		
		private var _radius:int;
		private var vertices:int;
		private var sideLength:Number;
		private var turnAngle:Number;
		private var currentAngle:Number;
		
		private var currentStep:Number;
		
		public function GeomPath(vertices:int, radius:int) 
		{
			this.vertices = vertices;
			this.radius = radius;
		}	
		public function set radius(radius:int):void 
		{
			calculateGeometry(radius);
			currentStep = 0;
			currentAngle = 0;
			_radius = radius;
		}
		
		/* INTERFACE enemies.IStrategyImplementation */
		public function perform(on:Entity):Boolean 
		{
			var totalSteps:int = Math.round(sideLength / on.speed);
			
			if (++currentStep >= totalSteps)
			{
				currentAngle += turnAngle;
				on.rotation = currentAngle;
				if (currentAngle >= Constants.TWO_PI) return true;
				currentStep = 0;
			}
			
			on.x += Math.cos(on.rotation) * on.speed;
			on.y += Math.sin(on.rotation) * on.speed;
			
			return false;
		}
		
		//helpers
		//defines sideLength and turn angle
		private function calculateGeometry(radius:int):void 
		{
			var perimeter:Number = 0;
			var segment:Number = Constants.TWO_PI / vertices;
			for (var theta:Number = 0; 
				theta < Constants.TWO_PI; 
				theta += segment)
			{
				var vertex:Point = Point.polar(radius, theta);
				points.push(vertex);
				if (points.length > 1)
				{
					var currentVertex:Point  = points[points.length-1];
					var previousVertex:Point = points[points.length-2];
					var side:Number = Point.distance(currentVertex, previousVertex);
					perimeter += side;
				}
			}
			this.turnAngle 	= segment;
			this.sideLength = perimeter / vertices;
		}
	}
}